<template>
<div class="about">
    <h1>{{id? '编辑':'创建'}}分类</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
        <el-form-item label="上级分类">
        <el-select v-model="model.parent" >
        <el-option v-for="item in parents" :key="item._id" :label="item.name" :value="item._id"></el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="名称">
            <el-input v-model="model.name"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" native-type="submit">提交</el-button>
        </el-form-item>
    </el-form>
</div>
</template>

<script>
export default {
    props:{
        id:{}
    },
    data(){
        return{
            model:{},
            parents:[]
            
        }
    },
    methods: {
        //保存表单
       async save(){
        let res
        //如果有id传入执行修改操作
        if(this.id){
        res = await this.$http.put(`categories/${this.id}`,this.model)   
        console.log(res)
        //没有id传入执行添加操作
        }else{
        res = await this.$http.post('categories',this.model)   
         console.log(res)

        }
        this.$router.push('/categories/list')
        this.$message({
            message:'success',
            type:'success'
        })
        },
       async fetch(){
           const model = await this.$http.get(`categories/${this.id}`)
        //    console.log(model)
            this.model = model.data

        },
       async fetchparentOption(){
           const res = await this.$http.get('categories')
            this.parents = res.data
            // console.log(res)
        }
    },
    created(){
        this.fetchparentOption()
        this.id && this.fetch()
    }
}
</script>

<style>

</style>